<template>
  <div class="summary">
    <div class="graph-wrapper">
      <div class="graph">
        <div class="header">
          <div class="title">客户地区分布</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              v-model="graphStatusList[0]['date']"
              @change="initDatas(0)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts echart1" :ref="el => setChartRef(el, 0)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">客户意向车型</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[1]['date']"
              @change="initDatas(1)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 1)"></div>
      </div>
    </div>
    <div class="graph-3r-wrapper">
      <div class="graph">
        <div class="header">
          <div class="title">客户状态</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[2]['date']"
              @change="initDatas(2)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 2)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">项目阶段</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[3]['date']"
              :clearable="false"
              @change="initDatas(3)"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 3)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">客户行业</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[4]['date']"
              :clearable="false"
              @change="initDatas(4)"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 4)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">客户来源</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[5]['date']"
              :clearable="false"
              @change="initDatas(5)"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 5)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">客户星级</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[6]['date']"
              :clearable="false"
              @change="initDatas(6)"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 6)"></div>
      </div>

      <div class="graph">
        <div class="header">
          <div class="title">客户类型</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[7]['date']"
              :clearable="false"
              @change="initDatas(7)"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 7)"></div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="reportSummary">
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import * as echarts from "echarts";
import { useEcharts } from "@/hooks/useEcharts";
import dayjs from "dayjs";
import {
  companyType,
  companyStatus,
  companyStage,
  companySource,
  companyProduct,
  companyIndustry,
  companyImportance,
  companyCity
} from "@/api/modules/statistics";
import { Dict } from "@/api/interface";
import { getParamByParentIdList } from "@/api/modules/sys";

const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
let dictList: Dict.ResDictList = reactive({});
let timer: NodeJS.Timer;
const startTime = dayjs().subtract(1, "year").format("YYYY-MM-DD HH:mm:ss");
const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");

// echarts通用配置

const graphStatusList = ref([
  { date: [startTime, endTime], data: {}, fetchData: companyCity },
  { date: [startTime, endTime], data: {}, fetchData: companyProduct },
  { date: [startTime, endTime], data: {}, dic: dict.customerStatus, fetchData: companyStatus },
  { date: [startTime, endTime], data: {}, dic: dict.customerStage, fetchData: companyStage },
  { date: [startTime, endTime], data: {}, dic: dict.industry, fetchData: companyIndustry },
  { date: [startTime, endTime], data: {}, dic: dict.customerSource, fetchData: companySource },
  { date: [startTime, endTime], data: {}, dic: "important", fetchData: companyImportance },
  { date: [startTime, endTime], data: {}, dic: dict.customerType, fetchData: companyType }
]);

// 获取字典数据
const getDicList = async (params: Dict.ResDictList) => {
  const { data } = await getParamByParentIdList(params);
  return data || [];
};

// 转换显示
const conversionDisplay = (id: string, type: string) => {
  if (type === "important") {
    return `${id}星`;
  }
  const listItem = dictList[type]?.find(item => item.id === id);
  return listItem?.name;
};

const chartRefs = ref<(HTMLElement | null)[]>([]);
const setChartRef = (el: HTMLElement | null, index: number) => {
  chartRefs.value[index] = el;
};

// 初始化图标数据
const initDatas = async (index: number | null = null) => {
  if (index === null) {
    for (let i = 0; i < graphStatusList.value.length; i++) {
      await fetchData(i);
    }
  } else {
    await fetchData(index);
  }
};

const fetchData = async (index: number) => {
  const { date, fetchData } = graphStatusList.value[index];
  const [startTime, endTime] = date;
  const { data } = await fetchData({ startTime, endTime });

  const eData = data.map(item => {
    const name = item.city || item.name || conversionDisplay(item.type || "", graphStatusList.value[index]["dic"]);
    return {
      name,
      value: item.value
    };
  });
  graphStatusList.value[index].data = eData;
};

// 初始化所有图表
const initChart = async () => {
  const getBarOption = (data: any) => {
    return {
      grid: { left: 30, right: 20, top: 20, bottom: 20 },
      tooltip: {
        trigger: "item",
        axisPointer: { type: "shadow" }
      },
      xAxis: {
        type: "category",
        data: data.map(item => item.name || ""),
        axisTick: { show: false },
        axisLine: { lineStyle: { color: "#EBEBEB" } },
        axisLabel: { color: "#333333", interval: 0 }
      },
      //      interval: 1,
      yAxis: {
        type: "value",
        axisLine: { show: true, lineStyle: { color: "#EBEBEB" } },
        axisTick: { show: true },
        splitLine: { show: false },
        axisLabel: { color: "#333333" }
      },
      series: {
        type: "bar",
        itemStyle: { color: (params: any) => (params.dataIndex === 0 ? "#5378F6" : "#ECF1F5") },
        emphasis: { disabled: true },
        barWidth: 20,
        data
      }
    };
  };
  const getPieOption = (data: any) => {
    return {
      color: ["#74D98C", "#5378F6", "#F8D27C", "#F56C6C"],
      legend: {
        icon: "circle",
        orient: "vertical",
        right: 10, // 图例距离右侧的距离
        top: "center", // 图例居中显示
        formatter: name => {
          const value = data.find(item => item.name === name).value;
          const percent = ((value / data.reduce((acc, curr) => acc + curr.value, 0)) * 100).toFixed(2);
          return `${name} ${value} ${percent}%`;
        },
        data: data.map(item => item.name || "") // 图例的数据来源
      },
      xAxis: { show: false },
      yAxis: { show: false },
      series: {
        label: {
          position: "center",
          formatter: () => {
            const totalValue = data.reduce((acc, curr) => acc + curr.value, 0);
            return `{a|${totalValue}}{b|个}`;
          },
          rich: {
            a: {
              fontSize: 20, // 数值部分的字体大小
              fontWeight: "bold" // 数值部分的字体加粗
            },
            b: {
              fontSize: 14 // 单位部分的字体大小
            }
          }
        },
        type: "pie",
        radius: ["45%", "75%"],
        center: ["40%", "50%"],
        data
      }
    };
  };
  chartRefs.value.map((chartRef, index) => {
    const myChart: echarts.ECharts = echarts.init(chartRef as HTMLElement);
    let option = {};
    if ([6, 7].includes(index)) {
      option = getPieOption(graphStatusList.value[index]["data"]);
    } else {
      option = getBarOption(graphStatusList.value[index]["data"]);
    }
    useEcharts(myChart, option);
  });
};

// 获取所有数据字典 缺少地区
const getAlldir = async () => {
  const list: string[] = [
    dict.customerType,
    dict.customerStatus,
    dict.customerStage,
    dict.customerSource,
    dict.customerQuality,
    dict.customerRating,
    dict.industry,
    dict.importance
  ];
  dictList = await getDicList({ parentIdList: list.join(",") });
};

onMounted(() => {
  getAlldir();
  initDatas();
  timer = setInterval(() => {
    initChart();
  }, 1000);
});
onUnmounted(() => {
  clearInterval(timer);
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
